package com.sky.service.admin.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.config.ThreadConfig;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.exception.MerchantNotFoundException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.admin.OrderMapper;
import com.sky.pojo.Orders;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    /**
     * 条件搜索订单
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> search(OrdersPageQueryDTO dto) {
        log.info("分页查询订单:{}",dto);
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> page=orderMapper.search(dto);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return Result.success(pageResult);
    }

    /**
     * 统计订单信息
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        log.info("订单数量统计");
        // 根据状态，   2 用户付款成功，等待商家接单  3.商家接单，等待骑手接单
        //     4 骑手接单成功-待取货  5待送达  6已完成  7已取消
        /*Integer waiting4MerchantReceiveOrders = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer waitng4RiderReceiveOrders = orderMapper.countStatus(Orders.CONFIRMED);
        Integer toBeDeliveryOnProgressOrders = orderMapper.countStatus(Orders.TOBEPICKEDUP);
        Integer toBeArrivedOrders = orderMapper.countStatus(Orders.TOBEDELIVERED);
        Integer completedOrders = orderMapper.countStatus(Orders.COMPLETE_ORDER);
        Integer canceledOrders = orderMapper.countStatus(Orders.CANCELLED_ORDER);*/

        /**
         * 线程池优化性能
         */
        Future<Integer> future1 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        });
        Future<Integer> future2 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.CONFIRMED);
        });
        Future<Integer> future3 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TOBEPICKEDUP);
        });
        Future<Integer> future4 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TOBEDELIVERED);
        });
        Future<Integer> future5 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.COMPLETE_ORDER);
        });
        Future<Integer> future6 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.CANCELLED_ORDER);
        });
        Integer waiting4MerchantReceiveOrders = null;
        Integer waitng4RiderReceiveOrders = null;
        Integer toBeDeliveryOnProgressOrders = null;
        Integer toBeArrivedOrders = null;
        Integer completedOrders = null;
        Integer canceledOrders = null;
        try {
            waiting4MerchantReceiveOrders = future1.get();
            waitng4RiderReceiveOrders = future2.get();
            toBeDeliveryOnProgressOrders = future3.get();
            toBeArrivedOrders = future4.get();
            completedOrders = future5.get();
            canceledOrders = future6.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)//  status = 2  等待商家接单
                .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)//  status = 3  等待骑手接单
                .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)//  status = 4  待出货订单数
                .toBeArrivedOrders(toBeArrivedOrders)//  status = 5  待送达订单数
                .completedOrders(completedOrders) // status = 6  已完成订单数
                .canceledOrders(canceledOrders)//  status = 7  已取消订单数
                .build();
        return orderStatisticsVO;
    }

    /**
     * 根据订单号查询订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrderVO getByOrderId(Long orderId) {
        log.info("根据订单号查询订单详情:{}",orderId);
        OrderVO orderVO=orderMapper.getByOrderId(orderId);
        return orderVO;
    }

    /**
     * 取消订单
     * @param dto
     */
    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        log.info("取消订单:{}",dto);
        //修改订单信息
        Orders orders = orderMapper.getOrders(dto.getId());
        if(orders.getStatus()==1||orders.getStatus()==6||orders.getStatus()==7||orders.getStatus()==8){
            throw new MerchantNotFoundException("-------订单状态不正确，无法取消-------");
        }

        orders.setCancelReason(dto.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLING);  //状态8，取消中，等待退款成功
        String number = orders.getNumber();
        Integer status = orders.getStatus();
        orderMapper.cancelOrder(status, number);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        log.info("拒单:{}",ordersRejectionDTO);
        // 根据id查询订单
        Orders ordersDB = orderMapper.getOrders(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            //这里模拟微信退款，实际开发中需要调用微信退款接口
            log.info("申请退款");
        }
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLING);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }
}
